<template>
  <el-dialog
    v-model="visible"
    title="投递简历"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="选择简历" prop="resumeId">
        <el-select
          v-model="formData.resumeId"
          placeholder="请选择要投递的简历"
          style="width: 100%"
          :loading="resumesLoading"
        >
          <el-option
            v-for="resume in resumes"
            :key="resume.id"
            :label="resume.resume_name"
            :value="resume.id"
          >
            <div class="resume-option">
              <span>{{ resume.resume_name }}</span>
              <span class="resume-status">
                <el-tag v-if="resume.status === 2" type="success" size="small">已完成</el-tag>
                <el-tag v-else-if="resume.status === 3" type="primary" size="small">已发布</el-tag>
                <el-tag v-else type="info" size="small">草稿</el-tag>
              </span>
            </div>
          </el-option>
        </el-select>
        <div class="tip-text">
          <el-link type="primary" :underline="false" @click="goToResumeList">没有简历？去创建</el-link>
        </div>
      </el-form-item>

      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系电话" />
      </el-form-item>

      <el-form-item label="邮箱地址" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱地址" />
      </el-form-item>

      <el-form-item label="求职信" prop="coverLetter">
        <el-input
          v-model="formData.coverLetter"
          type="textarea"
          :rows="4"
          placeholder="可选，可以写一些自我介绍或想对公司说的话"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确认投递</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import instance from '@/utils/request'
import useStore from '@/store'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  jobId: {
    type: [Number, String],
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const router = useRouter()
const store = useStore()

const visible = ref(false)
const formRef = ref(null)
const resumesLoading = ref(false)
const submitLoading = ref(false)
const resumes = ref([])

const formData = ref({
  resumeId: null,
  phone: '',
  email: '',
  coverLetter: ''
})

const rules = {
  resumeId: [
    { required: true, message: '请选择要投递的简历', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 获取简历列表
const fetchResumes = async () => {
  resumesLoading.value = true
  try {
    const response = await instance.request({
      method: 'GET',
      url: '/resumes'
    })
    
    if (response.code === 0) {
      // 后端返回的数据结构是 { total, page, pageSize, list: [] }
      const resumeList = response.data?.list || []
      
      // 放宽过滤条件：显示所有可用简历（不再按 status 过滤）
      resumes.value = Array.isArray(resumeList) 
        ? resumeList
        : []
      
      if (resumes.value.length === 0) {
        ElMessage.warning('您还没有可用的简历，请先创建简历')
      }
    } else {
      ElMessage.error(response.msg || '获取简历列表失败')
      resumes.value = []
    }
  } catch (error) {
    console.error('获取简历列表失败:', error)
    ElMessage.error('获取简历列表失败，请重试')
  } finally {
    resumesLoading.value = false
  }
}

// 初始化表单数据
const initForm = () => {
  formData.value = {
    resumeId: null,
    phone: store.app.userInfo?.phone || '',
    email: store.app.userInfo?.email || '',
    coverLetter: ''
  }
  
  // 如果有用户信息，尝试自动填充
  if (store.app.userInfo) {
    formData.value.phone = store.app.userInfo.phone || ''
    formData.value.email = store.app.userInfo.email || ''
  }
}

// 监听 visible 变化
watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
  if (newVal) {
    initForm()
    fetchResumes()
  }
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

// 提交投递
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 检查是否登录
    if (!store.app.userId || !store.app.token) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    
    submitLoading.value = true
    
    const response = await instance.request({
      method: 'POST',
      url: `/jobs/${props.jobId}/apply`,
      data: {
        resumeId: formData.value.resumeId,
        phone: formData.value.phone,
        email: formData.value.email,
        coverLetter: formData.value.coverLetter
      }
    })
    
    if (response.code === 0) {
      ElMessage.success('投递成功！')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(response.msg || '投递失败')
    }
  } catch (error) {
    if (error.response) {
      ElMessage.error(error.response.data?.msg || '投递失败')
    } else if (error.message !== 'validation failed') {
      console.error('投递失败:', error)
      ElMessage.error('投递失败，请重试')
    }
  } finally {
    submitLoading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 跳转到简历列表
const goToResumeList = () => {
  handleClose()
  router.push('/resume/my-resumes')
}
</script>

<style lang="scss" scoped>
.resume-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .resume-status {
    margin-left: 10px;
  }
}

.tip-text {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  text-align: right;
}
</style>

